package org.molehill
{
	import com.liu.load.LoadInfo;
	import com.liu.load.LoadManager;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display3D.Context3D;
	import flash.display3D.Context3DTextureFormat;
	import flash.display3D.textures.Texture;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	public class TexturePool
	{
		private var _baseUrl:String = 'file:///D:/role/';
		
		private var _context:Context3D;
		
		private var dic:Object;
		
		private var _roleDic:Object;
		private var _roleTexture:Texture;
		[Embed(source='assets/role/roledefault.png')]
		private var _roleDefault:Class;
		
		
		public static var instance:TexturePool;
		public function TexturePool(context:Context3D)
		{
			this._context = context;
			dic = new Object;
			initRole();
		}
		
		public function getTexture(key:String):Texture{
			if(dic.hasOwnProperty(key)){
				return dic[key];
			}else{
				return null;
			}
		}
		public function addTexture(key:String,texture:Texture):void{
			dic[key] = texture;
		}
		
		private function initRole():void{
			_roleDic = new Object;
			var bitmapdata:BitmapData = Bitmap(new _roleDefault()).bitmapData;
			_roleTexture = _context.createTexture(128,128, Context3DTextureFormat.BGRA, false);
			_roleTexture.uploadFromBitmapData(bitmapdata);
		}
		
		public function getRoleTexture(key:String):Texture{
			return _roleDic[key];
		}
		
		public function regist(key:String,w:int,h:int):void{
			var newkey:String = key + "*0_0";
			if(_roleDic.hasOwnProperty(newkey)){
				return;
			}
			var wNum:int = w/120;
			var hNum:int = h/120;
			for(var i:int=0;i<wNum;i++){
				for(var j:int=0;j<hNum;j++){
					newkey = key + "*" + i + "_" + j;
					_roleDic[newkey] = _roleTexture;
				}
			}
			
			var loadinfo:LoadInfo = new LoadInfo(_baseUrl+key+'.png',LoadInfo.BITMAP,onLoadRole,false,key);
			LoadManager.getInstance().addSingleLoad(loadinfo);
			
		}
		
		public function onLoadRole(bitmap:Bitmap,key:String):void{
			var newkey:String = key + "*0_0";
			var bitmapdata:BitmapData = bitmap.bitmapData;
			var newbitmapdata:BitmapData;
			
			var wNum:int = bitmapdata.width/120;
			var hNum:int = bitmapdata.height/120;
			
			var rec:Rectangle = new Rectangle(0,0,120,120);
			var p:Point = new Point;
			
			for(var i:int=0;i<wNum;i++){
				for(var j:int=0;j<hNum;j++){
					newkey = key + "*" + i + "_" + j;
					newbitmapdata = new BitmapData(120,120);
					rec.x = i*120;
					rec.y = j*120;
					newbitmapdata.copyPixels(bitmapdata,rec,p);
					var texture:Texture = _context.createTexture(128,128, Context3DTextureFormat.BGRA, false);
					texture.uploadFromBitmapData(newbitmapdata);
					_roleDic[newkey] = texture;
				}
			}
			
		}
		
	}
}